const nodemailer = require('nodemailer');
const crypto = require('crypto');

class EmailService {
	constructor() {
		// 创建邮件传输对象
		this.transporter = nodemailer.createTransport({
			host: 'smtp.qq.com', //QQ邮箱的 smtp 服务器地址
			secure: true, //使用 SSL 协议
			secureConnection: false, //是否使用对 https 协议的安全连接
			port: 465, //QQ邮件服务所占用的端口
			auth: {
				user: process.env.EMAIL_USER,
				pass: process.env.EMAIL_PASS
			}
		});
	}

	// 生成6位随机验证码
	generateVerificationCode() {
		return Math.floor(100000 + Math.random() * 900000).toString();
	}

	// 发送验证码邮件
	async sendVerificationCode(email, type) {
		const code = this.generateVerificationCode();
		const subject = this.getSubjectByType(type);
		const html = this.getEmailTemplate(type, code);

		try {
			await this.transporter.sendMail({
				from: process.env.EMAIL_USER,
				to: email,
				subject: subject,
				html: html
			});

			// 将验证码存储到Redis，设置5分钟过期
			const redisClient = require('../config/redis_config');
			const key = `email:${type}:${email}`;
			await redisClient.setEx(key, 300, code);

			return true;
		} catch (error) {
			console.error('发送邮件失败:', error);
			throw new Error('发送邮件失败');
		}
	}

	// 验证验证码
	async verifyCode(email, code, type) {
		const redisClient = require('../config/redis_config');
		const key = `email:${type}:${email}`;
		const storedCode = await redisClient.get(key);
		if (!storedCode || storedCode !== code) {
			throw new Error('验证码错误或已过期');
		}

		// 验证成功后删除验证码
		await redisClient.del(key);
		return true;
	}

	// 根据类型获取邮件主题
	getSubjectByType(type) {
		const subjects = {
			'bind': '邮箱绑定验证码',
			'change': '邮箱换绑验证码',
			'reset-password': '密码重置验证码'
		};
		return subjects[type] || '验证码';
	}

	// 获取邮件模板
	getEmailTemplate(type, code) {
		const templates = {
			'bind': `
                <h2>邮箱绑定验证</h2>
                <p>您的验证码是：<strong>${code}</strong></p>
                <p>验证码5分钟内有效，请尽快完成验证。</p>
            `,
			'change': `
                <h2>邮箱换绑验证</h2>
                <p>您的验证码是：<strong>${code}</strong></p>
                <p>验证码5分钟内有效，请尽快完成验证。</p>
            `,
			'reset-password': `
                <h2>密码重置验证</h2>
                <p>您的验证码是：<strong>${code}</strong></p>
                <p>验证码5分钟内有效，请尽快完成验证。</p>
            `
		};
		return templates[type] || `
            <h2>验证码</h2>
            <p>您的验证码是：<strong>${code}</strong></p>
            <p>验证码5分钟内有效，请尽快完成验证。</p>
        `;
	}
}

module.exports = new EmailService();